<template>
  <d2-container>
    <template slot="header">
      <div class="header">
        <h1>课程标签</h1>
        <div>
          <el-form
            :inline="true"
            :model="queryForm"
            class="demo-form-inline query_form"
            ref="queryForm"
          >
            <el-form-item class="query_item" prop="skillName" size="small" label="标签名称">
              <el-input v-model="queryForm.skillName" placeholder="标签名称" :clearable="true"></el-input>
            </el-form-item>
            <el-form-item class="query_item" size="small">
              <el-button type="primary" @click="querySkillBtn()">查询</el-button>
              <el-button @click="resetQueryForm('queryForm')">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="addSkillBtn()">添加标签</el-button>
        </div>
      </div>
    </template>
    <el-table
      class="table"
      :data="tableData"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        type="index"
        width="50"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-for="(val_en, key_ch) in colLabel"
        :key="val_en"
        :prop="key_ch"
        :label="val_en"
        min-width="150"
        sortable
        show-overflow-tooltip
        header-align="center"
      >
      </el-table-column>
      <el-table-column
        min-width="220"
        header-align="center"
        label="操作"
        fixed="right">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="detailSkillBtn(scope.$index, tableData)"
            type="default"
            size="small">
            详情
          </el-button>
          <el-button
            @click.native.prevent="updateSkillBtn(scope.$index, tableData)"
            type="primary"
            size="small">
            修改
          </el-button>
          <el-button
            @click.native.prevent="deleteSkillBtn(scope.$index, tableData)"
            type="danger"
            size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showUpdateDialog"
      width="30%"
      :before-close="handleClose"
      class="operate_dialog"
    >
      <div class="operate_skill" v-if="showUpdateDialog">
        <el-form
          ref="operateForm"
          :model="operateForm"
          :rules="skill_rules"
          :disabled="operateDisabled"
          label-width="auto"
          class="operate_form"
        >
          <div class="main">
            <el-form-item label="标签名称" prop="skillName">
              <el-input v-model="operateForm.skillName"></el-input>
            </el-form-item>
            <el-form-item label="删除标识" prop="delSign">
              <el-switch
                v-model="operateForm.delSign"
                active-value="1"
                inactive-value="0"
              ></el-switch>
            </el-form-item>
            <el-form-item label="标签介绍" prop="skillDetail">
              <el-input type="textarea" v-model="operateForm.skillDetail"></el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showUpdateDialog = false">取 消</el-button>
    <el-button type="primary" @click="DialogClick(operateForm)">确 定</el-button>
  </span>
    </el-dialog>
    <template slot="footer">
      <div class="pagination">
        <el-pagination
          background
          :current-page="page"
          :page-size="size"
          :pager-count="5"
          layout="prev, pager, next, jumper"
          :total="params.total"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </template>
  </d2-container>
</template>

<script>
import { GetSkill, AddSkill, UpdateSkill, DelSkill } from '@api/skill/index'

export default {
  name: 'index',
  data () {
    return {
      tableData: [],
      colName_ch: {
        skillId: '标签ID',
        skillName: '标签名称',
        createTime: '标签创建时间',
        createName: '标签创建人',
        updateTime: '标签修改时间',
        updateName: '标签修改人',
        delSign: '删除标识',
        skillDetail: '标签描述'
      },
      showLabel: [
        'skillName',
        'createTime',
        'createName',
        'updateTime',
        'updateName',
        'delSign',
        'skillDetail'
      ],
      params: {},
      queryForm: {
        skillName: ''
      },
      operateForm: {
        skillId: '',
        skillName: '',
        createTime: '',
        createName: '',
        updateTime: '',
        updateName: '',
        delSign: '',
        skillDetail: ''
      },
      page: 1,
      size: 12,
      showUpdateDialog: false,
      operateString: '',
      dialogTitle: '新增标签',
      skill_rules: {
        skillName: [
          {
            required: true,
            message: '标签名称不能为空',
            trigger: 'blur'
          },
          {}
        ],
        delSign: [
          {
            required: true,
            message: '删除标识不能为空',
            trigger: 'blur'
          }
        ]
      },
      operateDisabled: false
    }
  },
  methods: {
    /**
       * @description 调用api get接口，获取标签数据
       * @param {Object} params 查询参数
       * @return {Object} response 查询结果
       */
    async getSkillByApi (params) {
      let response
      await GetSkill(params).then(res => {
        response = res
      })
      return response
    },
    /**
       * @description 调用api add接口，添加一行数据
       * @param {Object} params 查询参数
       */
    async addSkillByApi (params) {
      await AddSkill(params).then(res => {
        console.log(res.data)
      })
    },
    /**
       * @description 调用api update接口，修改一行数据
       * @param {Object} params 修改参数
       */
    async updateSkillByApi (params) {
      await UpdateSkill(params).then(res => {
        console.log(res.data)
      })
    },
    /**
       * @description 调用api delete接口，将delSign设置为1
       * @param {Object} params 修改参数
       */
    async delSkillByApi (params) {
      await DelSkill(params).then(res => {
        console.log(res.data)
      })
    },
    /**
       * 根据查询参数和用户id获取tableData表格数据和total数据总数
       * @param {Object} params 查询参数
       */
    getSkill (params) {
      // 添加spId
      params['spId'] = 'user'
      this.getSkillByApi(params).then(res => {
        this.tableData = res.data.records
        this.params.total = res.data.total
      })
    },
    addSkill (formName) {
      this.$refs['operateForm'].validate((valid) => {
        if (valid) {
          this.params['skillName'] = this.operateForm.skillName
          this.params['skillDetail'] = this.operateForm.skillDetail
          this.params['delSign'] = this.operateForm.delSign
          // 仅用作测试------------
          this.params['createName'] = 'konrad'
          // -----------

          this.addSkillByApi(this.params).then(res => {
            // 关闭添加表单对话框
            this.closeOperateDialog()
            // 重新加载数据
            this.paramsClean()
            this.getSkill(this.params)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    updateSkill (params) {
      this.$refs['operateForm'].validate(valid => {
        if (valid) {
          this.updateSkillByApi(params).then(res => {
            this.closeOperateDialog()
            // 重新加载数据
            this.paramsClean()
            this.getSkill(this.params)
          })
        }
      })
    },
    delSkill (skillId) {
      this.delSkillByApi({ 'skillId': skillId }).then(res => {
        this.getSkill(this.params)
      })
    },
    addSkillBtn () {
      this.operateString = 'add'
      this.operateDisabled = false
      this.dialogTitle = '新增标签'
      this.operateForm = {}
      this.showUpdateDialog = true
    },
    updateSkillBtn (index, tableData) {
      this.operateString = 'update'
      this.operateDisabled = false
      this.dialogTitle = '修改标签'
      this.operateForm = tableData[index]
      this.showUpdateDialog = true
    },
    deleteSkillBtn (index, tableData) {
      this.delSkill(tableData[index].skillId)
    },
    detailSkillBtn (index, tableData) {
      this.operateString = 'detail'
      this.operateDisabled = true
      this.dialogTitle = '标签详情'
      this.operateForm = tableData[index]
      this.showUpdateDialog = true
    },
    DialogClick (params) {
      if (this.operateString === 'add') {
        this.addSkill(params)
      } else if (this.operateString === 'update') {
        this.updateSkill(this.operateForm)
      } else if (this.operateString === 'detail') {
        console.log('detail')
      }
    },
    querySkillBtn () {
      this.params['skillName'] = this.$refs['queryForm'].model.skillName
      this.getSkill(this.params)
    },
    /**
     * @description 重置查询表单
     * @param {String} formName 表单名
     */
    resetQueryForm (formName) {
      this.$refs[formName].resetFields()
      this.paramsClean()
      this.getSkill(this.params)
    },
    closeOperateDialog () {
      this.showUpdateDialog = false
    },
    showOperateDialog () {
      this.showUpdateDialog = true
    },
    /**
       * 【分页】点击页面，表格显示对应页面
       * @param page 点击页
       */
    handleCurrentChange (page) {
      this.page = page
      this.params.page = page
      this.getSkill(this.params)
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },
    paramsClean () {
      this.params = {}
      this.params.size = this.size
    }
  },
  computed: {
    /**
       * 根据showLabel(显示的标签)和tableData(表格数据)以及colName_ch(label中文对照)处理出一个{英文label:中文label}对象
       * @return {{}} {en_label:ch_label}
       */
    colLabel () {
      let data = {}
      for (let item of this.showLabel) {
        if (this.tableData.length >= 1 && this.tableData[0].hasOwnProperty(item)) {
          data[item] = this.colName_ch[item]
        }
      }
      return data
    }
  },
  created () {
    this.paramsClean()
    this.getSkill(this.params)
  }
}
</script>

<style scoped>
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 40px;
  }

  .header h1 {
    font-size: 1.6rem;
    font-weight: bold;
    margin: 0;
  }

  .header .query_form {
    display: inline-block;
    vertical-align: middle;
  }

  .header .query_form > div {
    margin: 0;
  }

  .header .query_item {
    margin-right: 20px !important;
  }

  .operate_skill {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .operate_skill .el-form {
    width: 75%;
    background-color: #fff;
    position: relative;
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
  }
</style>
